import axios from 'axios'
import store from '@/store'
import storage from 'store'
import Modal from 'ant-design-vue/es/modal'
import { VueAxios } from './axios'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import ServerConfig from '@/config/serverConfig'

const showError = function (content) {
  Modal.error({
    title: '发现异常',
    content: content,
    okText: '确定',
    centered: true
  })
}

// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  // baseURL: './',
    baseURL: './api',
  // headers: { 'X-Requested-With': 'XMLHttpRequest' },
  withCredentials: true,
  responseType: 'json',
  timeout: 6000 // 请求超时时间
})

// 异常拦截处理器
const errorHandler = (error) => {
  console.log(error)
  if (error.response) {
    const data = error.response.data
    // 从 localstorage 获取 token
    const token = storage.get(ACCESS_TOKEN)

    if (error.response.status === 403) {
      if (error.response.hideError !== true) {
        showError(data.message)
      }
      return
    }
    if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
      if (error.response.hideError !== true) {
        showError('登录超时')
      }
      if (token) {
        store.dispatch('Logout').then(() => {
          setTimeout(() => {
            window.location.reload()
          }, 1500)
        })
      }
      return
    }
    showError('服务器链接异常！')
  }
  showError('网络异常，请求超时！')
  return Promise.reject(error)
}

// request interceptor
request.interceptors.request.use(config => {
  if (!config.noToken) {
    const token = storage.get(ACCESS_TOKEN)
    // 如果 token 存在
    // 让每个请求携带自定义 token 请根据实际情况自行修改
    if (token) {
      config.headers[ServerConfig.token_header] = ServerConfig.basic_header_prefix + token
    }
  }
  return config
}, errorHandler)

// response interceptor
request.interceptors.response.use((response) => {
  const token = storage.get(ACCESS_TOKEN)
  const data = response.data
  const config = response.config
  const hideError = config.hideError
  if (data.success) {
    // return Promise.resolve(data.data)
    return data.data
  } else {
    if (data.code === 401) {
      if (hideError !== true) {
        if (data.msg === '无效的token') {
          store.dispatch('Logout').then(() => {
            setTimeout(() => {
              window.location.reload()
            }, 1500)
          })
        } else {
          showError(data.msg)
        }
      }
    } else if (data.code === 403) {
      if (hideError !== true) {
        showError('登录失败，请重新登录')
      }
      if (token) {
        store.dispatch('Logout').then(() => {
          setTimeout(() => {
            window.location.reload()
          }, 1500)
        })
      }
    } else if (data.msg === '无效的token') {
      store.dispatch('Logout').then(() => {
        setTimeout(() => {
          window.location.reload()
        }, 1500)
      })
    } else if (data.msg === '会员权限已过期') {
      // 权限问题不展示提示，由路由拦截
    } else {
      if (hideError !== true) {
        showError(data.msg)
      }
    }
    return Promise.reject(data)
  }
}, errorHandler)

const installer = {
  vm: {},
  install (Vue) {
    Vue.use(VueAxios, request)
  }
}

export default request

export {
  installer as VueAxios,
  request as axios
}
